import 'package:dio/dio.dart';
import 'package:slwl/utils/token.dart';

class NetworkService {
  final Dio dio = Dio();
  NetworkService() {
    dio.options.baseUrl = 'https://slwl-api.itheima.net'; // 基础URL
    dio.options.connectTimeout = const Duration(seconds: 20); // 连接超时时间
    dio.options.receiveTimeout = const Duration(seconds: 10); // 接收超时时间
    dio.options.headers = {'Content-Type': 'application/json'}; // 全局请求头

    _addInterceptors(); // 添加拦截器
  }

  void _addInterceptors() {
    dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) {
        // 在请求被发送之前做一些事情
        TokenManager tokenManager = TokenManager();
        String? token = tokenManager.getToken();
        if (token.isNotEmpty) {
          options.headers['Authorization'] = token;
        }
        return handler.next(options); // 继续发送请求
      },
      onResponse: (response, handler) {
        // 在响应被接收之前做一些事情
        return handler.next(response); // 继续处理响应
      },
      onError: (e, handler) {
        // 在请求失败时做一些事情
        return handler.next(e); // 继续处理错误
      },
    ));
  }

  //get请求
  Future<dynamic> get(String url, {Map<String, dynamic>? params}) async {
    try {
      dynamic response = await dio.get(url, queryParameters: params);
      return handleSuccess(response);
    } on DioException catch (e) {
      return handleError(e);
    }
  }

  //post请求
  Future<dynamic> post(String url, {dynamic data}) async {
    try {
      dynamic response = await dio.post(url, data: data);
      return handleSuccess(response);
    } on DioException catch (e) {
      return handleError(e);
    }
  }

  //put请求
  Future<dynamic> put(String url, {Map<String, dynamic>? data}) async {
    try {
      dynamic response = await dio.put(url, data: data);
      return handleSuccess(response);
    } on DioException catch (e) {
      return handleError(e);
    }
  }

  //delete请求
  Future<dynamic> delete(String url, {Map<String, dynamic>? data}) async {
    try {
      dynamic response = await dio.delete(url, data: data);
      return handleSuccess(response);
    } on DioException catch (e) {
      return handleError(e);
    }
  }

  //请求成功结果处理
  dynamic handleSuccess(Response response) {
    if (response.statusCode! >= 200 && response.statusCode! < 300) {
      return response.data;
    } else {
      return Exception('请求失败 状态码：${response.statusCode}');
    }
  }

  //请求失败结果处理
  dynamic handleError(DioException e) {
    if (e.type == DioExceptionType.connectionTimeout) {
      return Exception('连接超时');
    } else if (e.type == DioExceptionType.receiveTimeout) {
      return Exception('接收超时');
    } else if (e.type == DioExceptionType.sendTimeout) {
      return Exception('发送超时');
    } else if (e.type == DioExceptionType.cancel) {
      return Exception('请求取消');
    } else {
      if (e.response?.statusCode == 401) {
        //清除token
        TokenManager tokenManager = TokenManager();
        tokenManager.removeToken();
        // 跳转登录页;
      }
      return Exception('token失效');
    }
  }
}

final http = NetworkService();
